using DevExpress.Entity.Model.Metadata;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using twistmachinev2.CommonUse;
using twistmachinev2.OPCUA;

namespace twistmachinev2
{
    public partial class FrmAlarmInfo : BaseOpcUaForm
    {
        private DataTable alarmDataTable;
        private DynamicOpcUaMapper dynamicMapper;

        public FrmAlarmInfo()
        {
            InitializeComponent();
            InitializeAlarmData();

            // 延迟加载数据，确保窗体完全初始化
            this.Load += (s, e) =>
            {
                LoadAlarmNodes();
                UpdateAlarmData(); // 立即更新一次数据
            };
        }

        private void InitializeAlarmData()
        {
            // 创建数据表
            alarmDataTable = new DataTable();
            alarmDataTable.Columns.Add("NodeId", typeof(string));
            alarmDataTable.Columns.Add("Name", typeof(string));
            alarmDataTable.Columns.Add("CurrentValue", typeof(string));
            alarmDataTable.Columns.Add("AlarmStatus", typeof(string));
            alarmDataTable.Columns.Add("LastUpdate", typeof(string));
            alarmDataTable.Columns.Add("Description", typeof(string));



            // 配置GridView列
            ConfigureGridViewColumns();
            // 绑定数据源到Designer中定义的GridControl
            gridControl.DataSource = alarmDataTable;
            // 设置GridView事件
            gridView.RowStyle += GridView_RowStyle;

            // 报警数据表初始化完成
        }

        private void ConfigureGridViewColumns()
        {
            gridView.Columns.Clear();

            // 节点ID列
            GridColumn nodeIdColumn = gridView.Columns.AddVisible("NodeId", "节点ID");
            nodeIdColumn.Width = 200;
            nodeIdColumn.OptionsColumn.AllowEdit = false;

            // 名称列
            GridColumn nameColumn = gridView.Columns.AddVisible("Name", "报警名称");
            nameColumn.Width = 150;
            nameColumn.OptionsColumn.AllowEdit = false;

            // 当前值列
            GridColumn valueColumn = gridView.Columns.AddVisible("CurrentValue", "当前值");
            valueColumn.Width = 100;
            valueColumn.OptionsColumn.AllowEdit = false;

            // 报警状态列
            GridColumn statusColumn = gridView.Columns.AddVisible("AlarmStatus", "报警状态");
            statusColumn.Width = 100;
            statusColumn.OptionsColumn.AllowEdit = false;

            // 最后更新时间列
            GridColumn updateColumn = gridView.Columns.AddVisible("LastUpdate", "最后更新");
            updateColumn.Width = 150;
            updateColumn.OptionsColumn.AllowEdit = false;

            // 描述列
            GridColumn descColumn = gridView.Columns.AddVisible("Description", "描述");
            descColumn.Width = 200;
            descColumn.OptionsColumn.AllowEdit = false;
            descColumn.Visible = false; // 默认隐藏描述列

        }



        private void GridView_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                GridView view = sender as GridView;
                string alarmStatus = view.GetRowCellDisplayText(e.RowHandle, "AlarmStatus");

                if (alarmStatus == "报警")
                {
                    e.Appearance.BackColor = Color.FromArgb(255, 200, 200); // 浅红色
                    e.Appearance.ForeColor = Color.DarkRed;
                }
                else if (alarmStatus == "正常")
                {
                    e.Appearance.BackColor = Color.FromArgb(200, 255, 200); // 浅绿色
                    e.Appearance.ForeColor = Color.DarkGreen;
                }
            }
        }



        private void LoadAlarmNodes()
        {
            try
            {
                // 获取DynamicOpcUaMapper实例
                dynamicMapper = GetDynamicMapper();
                if (dynamicMapper == null)
                {
                    LogManager.LogError("无法获取DynamicOpcUaMapper实例");
                    return;
                }

                // 通过反射获取配置管理器
                var configManagerField = dynamicMapper.GetType().GetField("configManager",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                var configManager = configManagerField?.GetValue(dynamicMapper);

                if (configManager == null)
                {
                    LogManager.LogError("无法获取配置管理器实例");
                    return;
                }

                var getAllNodesMethod = configManager.GetType().GetMethod("GetAllNodes");
                var allNodeConfigs = getAllNodesMethod?.Invoke(configManager, null) as System.Collections.IEnumerable;

                if (allNodeConfigs == null)
                {
                    LogManager.LogError("无法获取节点配置列表");
                    return;
                }

                // 清空现有数据
                alarmDataTable.Clear();

                int alarmNodeCount = 0;

                // 筛选Group为"报警"的节点并添加到数据表
                foreach (var config in allNodeConfigs)
                {
                    if (config == null) continue;

                    // 获取Group属性值
                    var groupProperty = config.GetType().GetProperty("Group");
                    string groupValue = groupProperty?.GetValue(config)?.ToString();

                    // 只处理Group为"报警"的节点
                    if (string.Equals(groupValue, "报警", StringComparison.OrdinalIgnoreCase))
                    {
                        DataRow row = alarmDataTable.NewRow();

                        // 正确获取属性值
                        var nodeIdProperty = config.GetType().GetProperty("NodeId");
                        var nameProperty = config.GetType().GetProperty("Name");
                        var descriptionProperty = config.GetType().GetProperty("Description");

                        row["NodeId"] = nodeIdProperty?.GetValue(config)?.ToString() ?? "";
                        row["Name"] = nameProperty?.GetValue(config)?.ToString() ?? "";
                        row["CurrentValue"] = "--";
                        row["AlarmStatus"] = "未知";
                        row["LastUpdate"] = "--";
                        row["Description"] = descriptionProperty?.GetValue(config)?.ToString() ?? "";

                        alarmDataTable.Rows.Add(row);
                        alarmNodeCount++;
                    }
                }

                // 已加载报警节点

                // 刷新GridControl显示
                if (gridControl != null)
                {
                    gridControl.RefreshDataSource();
                    gridView.RefreshData();
                }

            }
            catch (Exception ex)
            {
                LogManager.LogError($"加载报警节点失败: {ex.Message}");
            }
        }

        private DynamicOpcUaMapper GetDynamicMapper()
        {
            if (dynamicMapper == null)
            {
                var serviceManager = twistmachinev2.OPCUA.OpcUaServiceManager.Instance;
                // 通过反射获取私有字段_dynamicMapper
                var field = serviceManager.GetType().GetField("_dynamicMapper",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                dynamicMapper = field?.GetValue(serviceManager) as DynamicOpcUaMapper;
            }
            return dynamicMapper;
        }

        /// <summary>
        /// 更新报警数据
        /// </summary>
        private void UpdateAlarmData()
        {
            try
            {
                var dataModel = GetDataModel("TwistMachine");
                if (dataModel != null)
                {
                    UpdateAlarmDataFromModel(dataModel);
                }
                else
                {
                    // 如果数据模型为空，尝试重新获取
                    // 数据模型为空，尝试重新获取
                    
                    // 等待一小段时间后重试
                    System.Threading.Tasks.Task.Delay(100).ContinueWith(_ => 
                    {
                        this.SafeInvoke(() => 
                        {
                            var retryDataModel = GetDataModel("TwistMachine");
                            if (retryDataModel != null)
                            {
                                UpdateAlarmDataFromModel(retryDataModel);
                            }
                        });
                    });
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError($"更新报警数据失败：{ex.Message}", ex);
            }
        }

        private string GetPropertyNameByNodeId(string nodeId)
        {
            try
            {
                if (dynamicMapper == null || string.IsNullOrEmpty(nodeId))
                    return null;

                // 通过反射获取配置管理器
                var configManagerField = dynamicMapper.GetType().GetField("configManager",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                var configManager = configManagerField?.GetValue(dynamicMapper);

                if (configManager == null)
                    return null;

                var getAllNodesMethod = configManager.GetType().GetMethod("GetAllNodes");
                var allNodeConfigs = getAllNodesMethod?.Invoke(configManager, null) as System.Collections.IEnumerable;

                if (allNodeConfigs == null)
                    return null;

                // 查找匹配的节点配置
                foreach (var config in allNodeConfigs)
                {
                    if (config == null) continue;

                    var nodeIdProperty = config.GetType().GetProperty("NodeId");
                    string configNodeId = nodeIdProperty?.GetValue(config)?.ToString();

                    if (string.Equals(configNodeId, nodeId, StringComparison.OrdinalIgnoreCase))
                    {
                        var propertyNameProperty = config.GetType().GetProperty("PropertyName");
                        return propertyNameProperty?.GetValue(config)?.ToString();
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                LogManager.LogError($"获取PropertyName失败: {ex.Message}");
                return null;
            }
        }

        private object GetModelValue(string propertyName)
        {
            var dataModel = GetDataModel("TwistMachine");
            try
            {
                if (dataModel == null || string.IsNullOrEmpty(propertyName))
                    return null;

                PropertyInfo property = dataModel.GetType().GetProperty(propertyName);
                return property?.GetValue(dataModel);
            }
            catch (Exception ex)
            {
                LogManager.LogError($"获取模型值失败 [{propertyName}]: {ex.Message}");
                return null;
            }
        }

        private string DetermineAlarmStatus(object value)
        {
            if (value == null)
                return "未知";

            // 对于布尔值，true表示报警，false表示正常
            if (value is bool boolValue)
            {
                return boolValue ? "报警" : "正常";
            }

            // 对于数值，可以根据具体业务逻辑判断
            if (value is int intValue)
            {
                return intValue > 0 ? "报警" : "正常";
            }

            // 对于字符串，可以根据具体内容判断
            string strValue = value.ToString();
            if (strValue.Equals("true", StringComparison.OrdinalIgnoreCase) ||
                strValue.Equals("1", StringComparison.OrdinalIgnoreCase) ||
                strValue.Equals("报警", StringComparison.OrdinalIgnoreCase))
            {
                return "报警";
            }

            return "正常";
        }

        /// <summary>
        /// 从数据模型更新报警数据
        /// </summary>
        /// <param name="dataModel"></param>
        private void UpdateAlarmDataFromModel(DynamicDataModel dataModel)
        {
            if (alarmDataTable == null || gridControl == null || dataModel == null)
            {
                // UpdateAlarmDataFromModel: 参数检查失败
                return;
            }

            try
            {
                // 暂停数据绑定以提高性能
                gridControl.BeginUpdate();

                int updatedCount = 0;
                foreach (DataRow row in alarmDataTable.Rows)
                {
                    string nodeId = row["NodeId"].ToString();

                    // 根据NodeId找到对应的PropertyName
                    string propertyName = GetPropertyNameByNodeId(nodeId);
                    if (!string.IsNullOrEmpty(propertyName))
                    {
                        // 从数据模型获取当前值
                        object currentValue = dataModel.GetValue(propertyName);
                        string valueStr = currentValue?.ToString() ?? "--";

                        // 更新当前值
                        row["CurrentValue"] = valueStr;

                        // 判断报警状态
                        string alarmStatus = DetermineAlarmStatus(currentValue);
                        row["AlarmStatus"] = alarmStatus;

                        // 更新时间
                        row["LastUpdate"] = DateTime.Now.ToString("HH:mm:ss");

                        updatedCount++;
                        
                        // 调试信息（只在调试模式下记录）
                        #if DEBUG
                        // 从数据模型更新报警数据
                        #endif
                    }
                    else
                    {
                        // 无法找到NodeId对应的PropertyName
                    }
                }

                // 恢复数据绑定并刷新显示
                gridControl.EndUpdate();
                gridView.RefreshData();
                
                // 报警数据更新完成
            }
            catch (Exception ex)
            {
                LogManager.LogError($"从数据模型更新报警数据失败: {ex.Message}", ex);
                // 确保在异常情况下也恢复数据绑定
                try { gridControl.EndUpdate(); } catch { }
            }
        }

        /// <summary>
        /// 处理数据变化（在UI线程上）
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="newValue"></param>
        protected override void OnDataChangedOnUIThread(string nodeId, object newValue)
        {
            base.OnDataChangedOnUIThread(nodeId, newValue);

            try
            {
                #if DEBUG
                // FrmAlarmInfo收到数据变化通知
                #endif
                
                // 通过数据模型来获取和更新数据
                var dataModel = GetDataModel("TwistMachine");
                if (dataModel != null)
                {
                    UpdateAlarmDataFromModel(dataModel);
                }
                else
                {
                    // OnDataChangedOnUIThread: 无法获取数据模型
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError($"处理数据变化事件失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 重写OnLoad方法，确保每次窗体显示时都能正确初始化数据
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            
            // 确保数据表已初始化
            if (alarmDataTable == null || alarmDataTable.Rows.Count == 0)
            {
                LoadAlarmNodes();
            }
            
            // 强制更新一次数据，确保显示最新值
            UpdateAlarmData();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // 清理资源
            alarmDataTable?.Dispose();

            base.OnFormClosing(e);
        }
    }
}
